# coding=utf-8
import hashlib
import json
from django.core.cache import cache
from django.db import transaction
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
import time
from com.kjssoft.rainbow import LOGGER
from com.kjssoft.rainbow.image.forms import ImageForm
from com.kjssoft.rainbow.image.models import RainbowImage
from com.kjssoft.rainbow.views import response_format_decorator

__author__ = 'Sea'

class RainbowImageJsonEncoder(json.JSONEncoder):
    def default(self, rainbow_image_instance):
        if isinstance(rainbow_image_instance, RainbowImage):
            rainbow_image_dict = {
                'id':rainbow_image_instance.id,
                'uuid':rainbow_image_instance.uuid,
                'width':rainbow_image_instance.width,
                'height':rainbow_image_instance.height,
                'size':rainbow_image_instance.size,
                'type':rainbow_image_instance.content_type.name,
            }
            return rainbow_image_dict
        elif isinstance(rainbow_image_instance, list) or isinstance(rainbow_image_instance, QuerySet):
            l = []
            for instance in rainbow_image_instance:
                l.append(self.default(instance))
            return l
        return super(RainbowImageJsonEncoder, self).default(rainbow_image_instance)


def model_instance_decorator(view_func):
    def _wrapper_view_func(request, instance_model_id, *args, **kwargs):
        LOGGER.debug(instance_model_id is not None)
        LOGGER.debug(type(instance_model_id))
        if instance_model_id is not None:
            try:
                instance_model_id = int(instance_model_id)
                instance_model = RainbowImage.objects.get(id = instance_model_id)
                return view_func(request, instance_model, *args, **kwargs)
            except ValueError as e:
                LOGGER.error(e)
            except RainbowImage.DoesNotExist as e:
                LOGGER.error(e)
        return redirect('/rainbow/image/404')
    return _wrapper_view_func

def list_view_page(request):
    pass

@response_format_decorator
@transaction.commit_on_success
def save_view_page(request):
    """
    保存图片
    """
    if request.POST:
        file_list = getattr(request.FILES, 'getlist')(ImageForm.IMAGE_FIELD_NAME)
        if len(file_list) > 1:
            image_models = ''
            for f in file_list:
                file_dict = {ImageForm.IMAGE_FIELD_NAME:f}
                imageForm = ImageForm(request.POST, file_dict)
                if imageForm.is_bound and imageForm.is_valid():
                    img = imageForm.cleaned_data.get(ImageForm.IMAGE_FIELD_NAME)
                    LOGGER.debug('uploaded file %s' % type(img))
                    image_model = RainbowImage.objects.create(img)
                    image_model.resize(900)
                    LOGGER.debug('%s uploaded' % image_model)
                    image_models += str(image_model.id)
                    image_models += ','
            if image_models.endswith(','):
                image_models = image_models[0:-1]
            LOGGER.debug('uploaded image models %s' % image_models)
            return redirect('/rainbow/image/list?instance_list=%s&format=%s' % (image_models, request.response_format))
        else:
            imageForm = ImageForm(request.POST, request.FILES)
            if imageForm.is_bound and imageForm.is_valid():
                img = imageForm.cleaned_data.get(ImageForm.IMAGE_FIELD_NAME)
                LOGGER.debug('uploaded file %s' % type(img))
                image_model = RainbowImage.objects.create(img)
                image_model.resize(900)
                LOGGER.debug(request.get_full_path())
                return redirect('/rainbow/image/%s/show?format=%s' % (image_model.id, request.response_format))
    md5 = hashlib.md5()
    md5.update(str(time.time()))
    csrftoken = request.COOKIES.get('csrftoken')
    if csrftoken:
        md5.update(csrftoken)
    imageForm = ImageForm(initial={
        'rainbow_image_progress' : md5.hexdigest()
    })
    return render_to_response(
        'kjs/rainbow/image/create.html',
        {'form':imageForm},
        context_instance = RequestContext(request)
    )

def progress_view_page(request):
    uploaded_progress = {}
    image_uploaded_progress_mark = request.GET.get(ImageForm.IMAGE_UPLOADED_PROGRESS_FIELD_NAME)
    if image_uploaded_progress_mark:
        uploaded_progress = cache.get(image_uploaded_progress_mark)
    return HttpResponse(json.dumps(uploaded_progress), mimetype='text/json')

@response_format_decorator
@model_instance_decorator
def show_view_page(request, instance_model=None):
    response_format = request.response_format
    if response_format == 'json':
        context = json.dumps(instance_model, cls=RainbowImageJsonEncoder)
        return HttpResponse(context, mimetype='text/json')
    return render_to_response(
        'kjs/rainbow/image/show.html',
        {'instance':instance_model},
        context_instance = RequestContext(request)
    )

@model_instance_decorator
@transaction.commit_on_success
def delete_view_page(request, instance_model=None):
    instance_model.delete()
    return render_to_response(
        'kjs/rainbow/image/delete.html',
        {'instance':instance_model},
        context_instance = RequestContext(request)
    )

def _404_view_page(request):
    return render_to_response(
        'kjs/rainbow/image/404.html',
        {},
        context_instance = RequestContext(request)
    )